﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using PessMvc.Models;
using System.Web.Profile;
using PessMvc.Helpers;

namespace MvcApplication4.Controllers
{
    public class AccountController : Controller
    {
        PessModel.PESSEntities db = new PessModel.PESSEntities();
        public ActionResult CountyAdmins()
        {
            //string[] usersInRole = Roles.GetUsersInRole("CountyAdmin");
            //MembershipUserCollection users = new MembershipUserCollection();
            
            //foreach (string userName in usersInRole)
            //{
            //    users.Add(Membership.GetUser(userName));
            //}
            
            //return View(users);

            string[] usersInRole = Roles.GetUsersInRole("CountyAdmin");

            IList<CountyAdminModel> countyAdmins = new List<CountyAdminModel>();

            foreach (string userName in usersInRole)
            {
                MembershipUser user=Membership.GetUser(userName);
                ProfileBase profile=ProfileBase.Create(userName);
                string countyCode=profile["CountyCode"].ToString();
                CountyAdminModel countyAdmin = new CountyAdminModel() {  
                    CountyCode=countyCode, 
                    Email=user.Email, 
                    UserName=user.UserName, 
                    CountyName=getCountyName(countyCode)
                };
                countyAdmins.Add(countyAdmin);
            }

            return View(countyAdmins);

        }

        private string getCountyName(string countyCode)
        {
            return db.Counties.Find(countyCode).Name;
        }

        public ActionResult CountyAdminRegister()
        {
            PessModel.PESSEntities db = new PessModel.PESSEntities();
            ViewData["Counties"] = new SelectList(db.Counties,"Code","Name");
            return View();
        }

        public ActionResult EditCountyAdmin(string userName)
        {
            MembershipUser user = Membership.GetUser(userName);
            ProfileBase profile=ProfileBase.Create(userName);

            string countyCode=profile["CountyCode"].ToString();
            CountyAdminModel countyAdmin = new CountyAdminModel() { CountyCode = countyCode, CountyName = getCountyName(countyCode), Email=user.Email, UserName=userName };

            return View(countyAdmin);
        }

        [HttpPost]
        public ActionResult EditCountyAdmin(CountyAdminModel model)
        {
            if (ModelState["EMail"].Errors.Count==0)
            {
                MembershipUser user=Membership.GetUser(model.UserName);
                user.Email = model.Email;
                Membership.UpdateUser(user);
            }

            return RedirectToAction("CountyAdmins");
        }
        [HttpPost]
        public ActionResult DeleteCountyAdmin(string userName)
        {
            Membership.DeleteUser(userName);
            return RedirectToAction("CountyAdmins");
        }

        [HttpPost]
        public ActionResult CountyAdminRegister(CountyAdminModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
                if(createStatus==MembershipCreateStatus.Success)
                {
                    Roles.AddUserToRole(model.UserName, "CountyAdmin");
                    ProfileBase profile=ProfileBase.Create(model.UserName);
                    profile["CountyCode"]=model.CountyCode;
                    profile.Save();

                    return RedirectToAction("CountyAdmins","Account");
                }
                else
                {
                    ModelState.AddModelError("",createStatus.ToString());
                }
               
            }

            // If we got this far, something failed, redisplay form
            return View(model);            
        }
        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                model.UserName = model.UserName.Trim();
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    
                    //This if guards the exception that expertjudge does not exist but user exists.
                    if (Roles.IsUserInRole(model.UserName,"ExpertJudge")&&db.ExpertJudges.Find(model.UserName) == null)
                    {
                        this.LogOff();                     
                    }

                    if (!Utility.IsExpertJudgeInfoComplete(model.UserName))
                    {
                        return RedirectToAction("EditExpertJudge", "ExpertJudge", new { serialNumber = model.UserName, returnUrl = returnUrl });
                    }
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Activity");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "用户名或密码错误。");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            HttpContext.Session["ActivityID"] = -1;
            return RedirectToAction("Index", "Activity");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion

        //public ActionResult Search(int activityID, string userName,string roleName)
        //{
        //    var users=Membership.GetAllUsers().
        //}

        public ActionResult ResetPassword(string userName,string returnUrl)
        {
            var user = Membership.GetUser(userName);
            user.UnlockUser();
            ResetPasswordModel model = new ResetPasswordModel() {
                UserName=user.UserName,
                 Roles=Roles.GetRolesForUser(userName).ToList(),
                 Password=user.ResetPassword(),
                  ActivityName=Roles.IsUserInRole(userName,"ExpertJudge")?db.ExpertJudges.Find(userName).ExpertGroups.FirstOrDefault().Activity.Name:"",
                  ReturnUrl=returnUrl
            };
            return View(model);
        }

        [HttpPost]
        public ActionResult ResetPassword(ResetPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                var user=Membership.GetUser(model.UserName);
                user.ChangePassword(user.ResetPassword(), model.Password);
                //return RedirectToAction("EditCountyAdmin", "Account", new { userName = model.UserName });
                return ReturnToUrl(model.ReturnUrl);
            }

            return View(model);
        }

        public ActionResult ReturnToUrl(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Activity");
            }
        }

        //public ActionResult ChangePassword()
        //{
        //    return View();
        //}

        //[HttpPost]
        //public ActionResult ChangePassword(LocalPasswordModel model)
        //{
        //    if (model.OldPassword == model.NewPassword)
        //    {
        //        ModelState.AddModelError("NewPassword", "New password is the same as the old one.");
        //    }
        //    if (ModelState.IsValid)
        //    {
        //        // ChangePassword will throw an exception rather
        //        // than return false in certain failure scenarios.
        //        bool changePasswordSucceeded;
        //        try
        //        {
        //            MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
        //            changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
        //        }
        //        catch (Exception)
        //        {
        //            changePasswordSucceeded = false;
        //        }

        //        if (changePasswordSucceeded)
        //        {
        //            return RedirectToAction("Logon");
        //        }
        //        else
        //        {
        //            ModelState.AddModelError("", "Wrong password.");
        //        }
        //    }

        //    // If we got this far, something failed, redisplay form
        //    return View(model);
        //}

        [Authorize]
        public ActionResult Settings()
        {
            return View();
        }
    }
}
